package com.xiwenlu.config;

import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.SerializationConfig;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;
import com.xiwenlu.annotation.EasyDictTypeToValue;

import java.util.ArrayList;
import java.util.List;

public class DicTypeBeanSerializerModifier extends BeanSerializerModifier {

    private final DictProvider dictProvider;

    public DicTypeBeanSerializerModifier(DictProvider dictProvider) {
        this.dictProvider = dictProvider;
    }

    @Override
    public List<BeanPropertyWriter> changeProperties(
            SerializationConfig config,
            BeanDescription beanDesc,
            List<BeanPropertyWriter> beanProperties) {

        List<BeanPropertyWriter> newWriters = new ArrayList<>();
        for (BeanPropertyWriter writer : beanProperties) {
            EasyDictTypeToValue ann = writer.getAnnotation(EasyDictTypeToValue.class);
            if (ann != null) {
                newWriters.add(new DicTypePropertyWriter(writer, ann.typeCode(),dictProvider));
            } else {
                newWriters.add(writer);
            }
        }
        return newWriters;
    }
}
